package player

import (
	"FlyFight/sql"
	"FlyFight/typego"
	"container/heap"
	"errors"
	"log"
	"sync/atomic"
)

//从数据库载入玩家
func loadPlayer(){
	players,err:=sql.LoadAllPlayer()
	if err!=nil{
		log.Println("加载玩家失败")
		return
	}
	if len(players)==0{
		log.Println("没有玩家")
		atomic.StoreInt32(&grouppool.Couter, 0)

		return
	}
	m:=0
	for _,p:=range players{
		m=max(m,p.Uid)
		grouppool.auth[p.Uid]=&p
	}
	grouppool.Buffer=make(MinHeap, 0,m+10-len(grouppool.auth))
	for i:=0;i<m+1;i++{
		if _,ok:=grouppool.auth[i];!ok{
			heap.Push(&grouppool.Buffer, i)
		}
	}
	atomic.StoreInt32(&grouppool.Couter, int32(m+1))
}

func Init(){
	grouppool.auth=make(map[int] *player)
	heap.Init(&grouppool.Buffer)
	loadPlayer()
}

func sqlCreat(p *typego.Player){
	if err:=sql.CreatePlayer(p);err!=nil{
		log.Println("创建用户失败")
	}
}

func CreatePlayer(usrname string) *typego.Player{
	var uid int
	if(grouppool.Buffer.Len()==0){
		uid=int(atomic.AddInt32(&grouppool.Couter,1))-1
	}else{
		uid=grouppool.Buffer.Pop().(int)
	}
	p:=new(typego.Player)
	p.Uid=uid
	p.KillNum=0
	p.InGame=false
	p.Changed=false
	p.UsrName=usrname

	grouppool.auth[uid]=p


	go sqlCreat(p)
	

	return p
}

//获取玩家击杀数量
func GetKillNum(uid int) int{
	if p,ok:=grouppool.auth[uid];ok{
		return p.KillNum
	}
	return -1
}

func GetName(uid int) (string,error){
	if p,ok:=grouppool.auth[uid];ok{
		return p.UsrName,nil
	}
	return "",errors.New("no such player")
}

